<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Notification;
use Illuminate\Http\Request;

class NotificationController extends BaseController
{
    protected $model = Notification::class;

    public function index(Request $request)
    {
        $input = $request->input();
        $search = ['title' => ''];
        $is_send = \request('is_send', -1);
        $start_at = \request('start_at');
        $end_at = \request('end_at');
        $type = $request->input('type', [Notification::TYPE_SYSTEM, Notification::TYPE_BACKEND_CREATE]);
        if (!is_array($type))
            $type = [$type];

        $list = Notification::apply($search, $input)->whereIn('type', $type)
            ->when($is_send != -1, function ($q) use($is_send) {
                $q->where('is_send', $is_send);
            })
            ->when($start_at, function ($q) use($start_at) {
                $q->where('updated_at', '>=', $start_at);
            })
            ->when($end_at, function ($q) use($end_at) {
                $end_at = date('Y-m-d', strtotime($end_at) + 24 * 3600);
                $q->where('updated_at', '<', $end_at);
            })
            ->orderBy('id', 'desc')
            ->paginate(\request('per_page', 20));

        $extra = null;
        return $this->paginate($list, $extra);
    }

    public function store(Request $request)
    {
        $input = $request->input();
        $id = \request("id");
        $input['type'] = Notification::TYPE_BACKEND_CREATE;
        $input['is_send'] = 0;
        if ($id) {
            $one = $this->model::find($id);
            if (!$one) {
                return $this->failed('ID不存在');
            }
            $one->update($input);
        } else {
            $info = $this->model::create($input);
            $id = $info->id;
        }
        return $this->success($id);
    }

    public function send(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = \request('ids');
        $arr_ids = explode(",", $ids);
        foreach ($arr_ids as $id) {
            $notification = Notification::find($id);
            if (!$notification || $notification->status == 1 || $notification->type != Notification::TYPE_BACKEND_CREATE)
                continue;
            else {
                $notification->is_send = 1;
                $notification->updated_at = date('Y-m-d H:i:s');
                $notification->save();
            }
        }
        return $this->success([]);
    }
}

